<template>
    <div class="container">

        <Amap ref="amap" :showSearch="false" :lng="lng" :lat="lat" @complete="handleComplete" style="height: 100%;">
        </Amap>

        <div v-if="isSearch" class="search-p">
            <Tree :base-list="baseList" :land-list="landList" @select="select"></Tree>
        </div>

        <div v-if="operateType == OperateTypeEnum.ADDING || operateType == OperateTypeEnum.EDITING" class="draw-tip">
            <a-space v-if="operateType == OperateTypeEnum.EDITING" style="padding: 0 0 20px 0;">
                <a-button @click="saveEdit" type="primary">保存</a-button>
                <a-button @click="deleteEdit" type="primary" danger>删除</a-button>
                <a-button @click="cancelEdit">取消</a-button>
            </a-space>
            <a-space v-else style="padding: 0 0 20px 0;">

                <a-button @click="cancelAdd">取消</a-button>
            </a-space>

            <div class="draw-tip-text"> {{ tipText }} </div>
        </div>

    </div>
</template>
<script lang="ts" setup>
import { ref, onActivated, onMounted, watch, withDirectives } from 'vue'
import Amap from '@/components/Amap/Amap.vue'


import markerBlue from '@/assets/map/marker-blue.png'
import markerGreen from '@/assets/map/marker-green.png'
import markerRed from '@/assets/map/marker-red.png'
import markerYellow from '@/assets/map/marker-yellow.png'
import type { Base } from '@/types/Base'
import type { Land } from '@/types/Land'
import { addBaseRange, addLandRange, addMarkerAndText } from './fenceUtils'
import { MapPoinitType } from './MapPointType'
import Tree from './tree.vue'
const props = withDefaults(defineProps<{
    baseList?: Base[],
    landList?: Land[],
    isSearch?: boolean,
    lng?: number,
    lat?: number
}>(), {
    isSearch: true,
    baseList: [],
    landList: []
})
const emit = defineEmits<{
    complete: [AMap.Map],
    search: [string],
    save: [Base | Land, AMap.Polygon],
    delete: [Base | Land]
}>()


const tipText = ref('鼠标左键点击地图绘制区域，双击击鼠标左键结束绘制')
const keyword = ref('')

const amap = ref()
let map: AMap.Map
let polyEditor: AMap.PolygonEditor
let mouseTool: AMap.MouseTool
let curExtData: Base | Land
let infoWindow: AMap.InfoWindow
enum OperateTypeEnum {
    NONE = 0,
    /**添加操作中 */
    ADDING = 1,
    /**修改操作中 */
    EDITING = 2,
    /**删除 */
    DELETE = 3,
    /**编辑 */
    SAVE = 4,
    /**取消 */
    CANCEL = 5
}

const operateType = ref<OperateTypeEnum>(OperateTypeEnum.NONE)



const handleComplete = (e: AMap.Map) => {
    map = e

    emit('complete', e)


}

const onSearch = () => {
    map.clearMap()
    emit('search', keyword.value)
}

const cancelAdd = () => {
    operateType.value = OperateTypeEnum.CANCEL
    mouseTool.close(true)


    showAll()
}

const saveEdit = () => {
    operateType.value = OperateTypeEnum.SAVE
    polyEditor.close()

}

const cancelEdit = () => {
    operateType.value = OperateTypeEnum.CANCEL
    polyEditor.close()

    //复原多边形
    let list = map.getAllOverlays('polygon')
    for (let item of list) {
        let _extData = item.getExtData()
        if (curExtData.id == _extData.id && curExtData.className == _extData.className) {

            let polyPath: [number, number][] = curExtData.scope!.map((obj) => {
                return [obj.lng, obj.lat];
            });
            item.setPath(polyPath)

        }
    }


}

const deleteEdit = () => {
    operateType.value = OperateTypeEnum.DELETE
    polyEditor.close()

    // infoWindow.close()

    curExtData.scope = []

    let list = map.getAllOverlays('polygon')
    for (let item of list) {
        let _extData = item.getExtData()
        if (curExtData.id == _extData.id && curExtData.className == _extData.className) {
            map.remove(item)
        }
    }

    list = map.getAllOverlays('marker')
    for (let item of list) {
        let _extData = item.getExtData()
        if (curExtData.id == _extData.id && curExtData.className == _extData.className) {
            item.setExtData(JSON.parse(JSON.stringify(curExtData)))
        }
    }
    emit('delete', curExtData)
    showAll()
}


watch(() => props.baseList, () => {
    if (!props.baseList) {
        return
    }
    let list = map.getAllOverlays()
    for (let item of list) {
        let _extData = item.getExtData()
        if (_extData.className == MapPoinitType.BASE) {
            map.remove(item)
        }
    }

    for (let item of props.baseList) {



        let icon = new AMap.Icon({
            size: new AMap.Size(25, 34), // 图标尺寸
            image: markerGreen,
            imageSize: new AMap.Size(25, 34),
        });


        let marker = new AMap.Marker({
            icon: icon,
            position: [item.lng!, item.lat!],
            anchor: 'bottom-center',
            extData: {
                className: MapPoinitType.BASE,
                ...item
            },
            map
        });

        marker.on('click', () => {
            select(MapPoinitType.BASE, item)
        })

        new AMap.Text({
            text: item.name + '（基地）',
            anchor: 'center', // 设置文本标记锚点
            angle: 0,
            offset: new AMap.Pixel(0, -60),
            style: {
                'text-align': 'center', background: '#2ebf2799', border: 'none', color: '#fff', 'font-size': '16px', 'box-shadow': '0 0 5px 0 rgba(0, 0, 0, 0.5)', padding: '5px 10px'

            },
            position: [item.lng!, item.lat!],
            zIndex: 10,
            map
        });


        if (item.scope && item.scope.length > 0) {
            let path = item.scope.map((obj) => {
                return new AMap.LngLat(obj.lng, obj.lat)
            })

            let polygon = new AMap.Polygon();
            polygon.setOptions({

                path: path, //设置多边形边界路径
                strokeColor: '#2ebf27', //线颜色
                strokeOpacity: 1, //线透明度
                strokeWeight: 1, //线宽
                fillColor: '#2ebf27', //填充色
                fillOpacity: 0.5, //填充透明度
                zIndex: 10,
                extData: {
                    className: MapPoinitType.BASE,
                    ...item
                }
            })
            map.add(polygon)

        }

    }
})
watch(() => props.landList, () => {
    if (!props.landList) {
        return
    }
    let list = map.getAllOverlays()
    for (let item of list) {
        let _extData = item.getExtData()
        if (_extData.className == MapPoinitType.LAND) {
            map.remove(item)
        }
    }
    for (let item of props.landList) {

        let icon = new AMap.Icon({
            size: new AMap.Size(25, 34), // 图标尺寸
            image: markerYellow,
            imageSize: new AMap.Size(25, 34),
        });


        let marker = new AMap.Marker({
            icon: icon,
            position: [item.lng!, item.lat!],
            anchor: 'bottom-center',
            extData: {
                className: MapPoinitType.LAND,
                ...item
            },
            visible: false,
            map
        });

        new AMap.Text({
            text: item.name + '（地块）',
            anchor: 'center', // 设置文本标记锚点
            angle: 0,
            offset: new AMap.Pixel(0, -60),
            style: {
                'text-align': 'center', background: '#d2a831cc', border: 'none', color: '#fff', 'font-size': '16px', 'box-shadow': '0 0 5px 0 rgba(0, 0, 0, 0.5)', padding: '5px 10px'

            },
            position: [item.lng!, item.lat!],
            zIndex: 100,
            visible: false,
            extData: {
                className: MapPoinitType.LAND,
                ...item
            },
            map
        });


        if (item.scope && item.scope.length > 0) {
            let path = item.scope.map((obj) => {
                return new AMap.LngLat(obj.lng, obj.lat)
            })

            let polygon = new AMap.Polygon();
            polygon.setOptions({
                path: path, //设置多边形边界路径
                strokeColor: '#d2a831', //线颜色
                strokeOpacity: 1, //线透明度
                strokeWeight: 1, //线宽
                fillColor: '#d2a831', //填充色
                fillOpacity: 0.5, //填充透明度
                zIndex: 100,
                
                extData: {
                    className: MapPoinitType.LAND,
                    ...item
                }
            })
            map.add(polygon)
            polygon.hide()

        }
    }
})

const onlyShowById = (id: number, className: string) => {
    let list = map.getAllOverlays()
    for (let item of list) {
        let _extData = item.getExtData()
        if (_extData.id == id && _extData.className == className) {
            item.show()
        } else {
            item.hide()
        }
    }
}
const showAll = () => {
    let list = map.getAllOverlays()
    for (let item of list) {
        item.show()
    }
}

const handleMarkerClick = (e: any) => {

    let target: AMap.Marker = e.target
    curExtData = target.getExtData()
    console.log('curExtData:', curExtData)
    onlyShowById(curExtData.id!, curExtData.className!)
    // infoWindow = new AMap.InfoWindow({
    //     anchor: 'top-center',
    // });
    if (curExtData.scope && curExtData.scope.length > 0) {
        operateType.value = OperateTypeEnum.EDITING
        let list = map.getAllOverlays('polygon')

        for (let item of list) {
            let _extData = item.getExtData()
            if (curExtData.id == _extData.id && curExtData.className == _extData.className) {
                // map.setFitView([item], false, [160, 160, 160, 160]);
                polyEditor = new AMap.PolygonEditor(map, item);
                polyEditor.open();
                // 结束编辑时，调用
                // polyEditor.close()

                polyEditor.on('end', (e) => {
                    let p: AMap.Polygon = e.target

                    if (operateType.value == OperateTypeEnum.SAVE) {
                        // save(curExtData, p)
                        emit('save', curExtData, p)

                    }
                    showAll()

                    // infoWindow.close()
                })
            }
        }


        tipText.value = '编辑完成后，点击保存按钮'

        // infoWindow.setContent("<div style='color:red;'>编辑完成后，点击右上角的保存按钮</div>")
        // infoWindow.open(map, target.getPosition()!.toArray())
    } else {
        // map.setFitView([target], false, [160, 160, 160, 160]);
        mouseTool = new AMap.MouseTool(map)
        operateType.value = OperateTypeEnum.ADDING
        if (curExtData.className == MapPoinitType.BASE) {
            mouseTool.polygon({
                fillColor: '#d6333f',
                strokeColor: '#d6333f',
                zIndex: 1,
                //同Polygon的Option设置
            });
        } else {
            mouseTool.polygon({
                fillColor: '#1791fc',
                strokeColor: '#1791fc',
                zIndex: 10,
                //同Polygon的Option设置
            });
        }

        mouseTool.on('draw', (e) => {
            mouseTool.close(false)
            let obj: AMap.Polygon = e.obj
            let path: AMap.LngLat[] = obj.getPath() as AMap.LngLat[]
            let scope = path.map(lngLat => {
                return {
                    lat: lngLat.lat,
                    lng: lngLat.lng
                }
            })
            curExtData.scope = scope
            console.log(curExtData)
            obj.setExtData(JSON.parse(JSON.stringify(curExtData)))
            target.setExtData(JSON.parse(JSON.stringify(curExtData)))
            // save(curExtData, obj)
            emit('save', curExtData, obj)
            showAll()
            operateType.value = OperateTypeEnum.NONE
            // infoWindow.close()
        })


        tipText.value = '鼠标左键点击地图绘制区域，双击击鼠标左键结束绘制'

        // infoWindow.setContent("<div style='color:red;'>鼠标左键点击地图绘制区域，双击击鼠标左键结束绘制</div>")
        // infoWindow.open(map, target.getPosition()!.toArray())
    }
}

const select = (type: MapPoinitType, data: Base | Land) => {
    console.log(type)
    console.log(data)
    let list = map.getAllOverlays('marker')
    for (let item of list) {
        let _extData = item.getExtData()
        if (_extData.className == type && _extData.id == data.id) {
            // map.setFitView([item])
            map.panTo([_extData.lng!, _extData.lat!], 1000)
        }
    }

    let overlays = map.getAllOverlays()
    for(let item of overlays){
        let _extData = item.getExtData()
        if(_extData.className == MapPoinitType.LAND){
            if(_extData.baseId == data.id){
                item.show()
            } else {
                item.hide()
            }
        }
    }
}

</script>
<style scoped>
.container {
    height: 100%;
    position: relative;
    overflow: hidden;
}


@keyframes beat {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

@-moz-keyframes beat

/* Firefox */
    {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

@-webkit-keyframes beat

/* Safari 和 Chrome */
    {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

@-o-keyframes beat

/* Opera */
    {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

.draw-tip {
    position: absolute;
    right: 5%;
    top: 10%;
    padding: 10px 20px;
    z-index: 10;
    background: #fff;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.5);
}

.draw-tip-text {
    color: #e73d4a;
    animation: beat 1s infinite;
    -moz-animation: beat 1s infinite;
    /* Firefox */
    -webkit-animation: beat 1s infinite;
    /* Safari 和 Chrome */
    -o-animation: beat 1s infinite;
}

.tip-text {
    display: inline-block;
    padding: 0 40px 0 0;
}

.search-p {
    padding: 10px 10px 10px 20px;
    box-shadow: 0 0 20px 0 rgba(0, 0, 0, 1);
    position: absolute;
    top: 20px;
    left: 20px;
    height: 85%;
    min-width: 250px;



    background: linear-gradient(to bottom, rgb(5, 79, 99), rgba(5, 79, 99, 0.5), rgb(5, 79, 99));
    border-radius: 1vh;
    border: 0.125vh solid rgb(6, 112, 180);

}
</style>